import type { Message } from "wukongimjssdk";
import WKSDK from "wukongimjssdk";
import KOCSIM from "../initKOCSIM";
import IMStore from "./store";
import config from "../config";

// 转换UI消息 和 WKSDK消息
export const convertMessage = (message: Message, fixedStatus?: string) => {
  // type: "image",
  //   content: imageUrl,
  //   from: "user",
  //   time: new Date().getTime(),
  //   avatar: "https://n.sinaimg.cn/sinacn/w960h1440/20171223/d7cd-fypvuqf4642780.png",

  const { content, channel, clientMsgNo, status, timestamp, contentType, send, messageSeq, clientSeq, messageID } = message;
  return {
    type: getMessageType(contentType),
    from: getMessageFrom(message),
    content: content,
    time: new Date(timestamp * 1000).getTime(),

    // 自定义
    status: fixedStatus ?? "success"/* "upload" */,
    process: 0,

    // 客户端发送消息 clientMsgNo ，查询历史消息 messageID
    messageID: messageID || clientMsgNo || '',

    name: getName(message),

    source: {
      // 消息内容
      content,
      // 消息通道
      channel,
      // 本地唯一ID
      clientMsgNo,
      // 消息状态 0.发送中 1.成功
      status,
      // 10位时间戳
      timestamp,
      // 消息正文类型 如 1:【文本】2:【图片】...
      contentType,
      //
      send,
    },
  };
};

export const messageTypeMap: Record<number, string> = {
  1: "text",
  2: "image",
  3: "voice",
  4: "video",
  101: "wecat-info",
  // 2100: "server-status",
  /** 客服进入 */
  2102: "server-status",
  /** 结束会话 */
  2101: "server-status",
};

const getMessageType = (contentType: number) => {
  const type = messageTypeMap[contentType];
  if (!type) {
    return "unknown";
  }
  return type;
};

const getMessageFrom = (message: Message) => {
  const { fromUID, contentType } = message;

  // 如果当前 fromUid 和 当前用户 uid 相同，则认为是用户发送的消息
  const uid = WKSDK.shared().config.uid;
  if (contentType === 1010) return "system";
  if (uid === fromUID) return "user";
  else return "service";
};

// 获取发信人名称
const getName = (message: Message) => {
  const channel = KOCSIM.inst().channelInfo;
  const self = message.fromUID === WKSDK.shared().config.uid;
 if (self) return channel.visitorName;

 // 查找当前通道列表客服和
 if (message.fromUID == KOCSIM.inst().currentService?.userId) return KOCSIM.inst().currentService?.servicePersonName;
 
 // 都没有名字，则返回默认名字
 return self ? config.chatConfig.defaultSelfName : config.chatConfig.defaultOtherName
};

// 将字符串转换为Uint8Array
export function stringToUint8Array(str: string) {
  const arr = [];
  for (let i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }
  const tmpUint8Array = new Uint8Array(arr);
  return tmpUint8Array;
}


// 防抖
export const debounce = (func: Function, wait: number) => {
  let timeout: any;
  return function (this: any, ...args: any[]) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
};


export const getUrlParams = () => {
  const url = window.location.href;
  const paramsString = url.split("?")[1]; // 获取问号之后的部分
  const searchParams = new URLSearchParams(paramsString);

  let params: any = {};
  for (let [key, value] of searchParams.entries()) {
    params[key] = decodeURIComponent(value); // 解码URL编码的字符
  }
  return params;
};

// 对象转url参数
export const objToUrlParams = (obj: any) => {
  return Object.keys(obj)
    .map((key) => `${key}=${encodeURIComponent(obj[key])}`)
    .join("&");
};

// 将毫秒转为 分'秒" 格式
export const formatTimePlay = (time: number) => {
  const minute = Math.floor(time / 1000 / 60);
  const second = Math.floor(time / 1000 % 60);
  // 如果 minute 为零，则直接返回秒数
  if (minute === 0) {
    return `${second}"`;
  }
  return `${minute}'${second}"`;
}
